// models/order.js (更新版)
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");

const Order = sequelize.define(
  "Order",
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: "订单唯一标识符",
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: "关联用户ID",
    },
    orderNumber: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: "订单号，系统生成的唯一标识",
    },
    totalAmount: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      validate: {
        min: 0,
      },
      comment: "订单总金额",
    },
    status: {
      type: DataTypes.ENUM(
        "pending",
        "confirmed",
        "processing",
        "shipped",
        "delivered",
        "cancelled",
        "refunded"
      ),
      defaultValue: "pending",
      comment: "订单状态",
    },
    shippingAddress: {
      type: DataTypes.JSON,
      allowNull: false,
      comment: "收货地址信息",
    },
    paymentMethod: {
      type: DataTypes.ENUM("credit_card", "paypal", "bank_transfer", "cod"),
      allowNull: false,
      comment: "支付方式",
    },
    paymentStatus: {
      type: DataTypes.ENUM("pending", "paid", "failed", "refunded"),
      defaultValue: "pending",
      comment: "支付状态",
    },
    // 其他订单相关字段...
  },
  {
    tableName: "orders",
    timestamps: true,
    comment: "订单表",
    indexes: [
      {
        name: "K_userId",
        fields: ["userId"],
      },
      {
        name: "K_orderNumber",
        fields: ["orderNumber"],
      },
      {
        name: "K_status",
        fields: ["status"],
      },
    ],
  }
);

// 订单关联定义
Order.associate = function (models) {
  // 一个订单属于一个用户
  Order.belongsTo(models.User, {
    foreignKey: "userId",
    as: "user",
  });

  // 一个订单可以有多个订单项
  Order.hasMany(models.OrderItem, {
    foreignKey: "orderId",
    as: "items",
  });
};

module.exports = Order;
